package com.xyx.bloodoxygenjava;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import android.Manifest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.xyx.bloodoxygenjava.devices.BLEManager;
import com.xyx.bloodoxygenjava.devices.DeviceListener;
import com.xyx.bloodoxygenjava.utils.BLEOpertion;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    /**
     * 蓝牙操作
     */
    private BLEOpertion opertion;
    /**
     * 查询按钮
     */
    private Button searchButton;
    /**
     * ble蓝牙适配器
     */
    private BluetoothAdapter mBluetoothAdapter;

    /**
     * tag
     */
    private static String TAG = "MainActivity";
    private BLEManager mManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        searchButton = findViewById(R.id.button);

        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "onClick: start searching......");
                opertion.startDiscover();
            }
        });

        try {
            Log.i(TAG, "can use : " + BLEOpertion.isCanUseBLE(this));
            opertion = new BLEOpertion(this, new DeviceListener());
        } catch (Exception e) {
            e.printStackTrace();
        }
        initBLE();
        android6_RequestLocation(this);
    }

    /**
     * android6.0 Bluetooth, need to open location for bluetooth scanning
     * android6.0 蓝牙扫描需要打开位置信息
     */
    private void android6_RequestLocation(final Context context){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            String[] permissions = checkSelfPermissionArray(
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_ADVERTISE,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissions.length > 0) {
                Log.i(TAG, "android6_RequestLocation: " + String.join(" ", permissions));
                ActivityCompat.requestPermissions(this, permissions, 0);
            }
        }

        if (Build.VERSION.SDK_INT >= 23) {
            // BLE device need to open location
            if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
                    && !isGpsEnable(context)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setCancelable(false);
                builder.setTitle("Prompt")
                        .setIcon(android.R.drawable.ic_menu_info_details)
                        .setMessage("Android6.0 need to open location for bluetooth scanning")
                        .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton("OK", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                // startActivityForResult(intent,0);
                                context.startActivity(intent);
                            }
                        });
                builder.show();
            }

            //request permissions
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要 向用户解释，为什么要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION))
                    Toast.makeText(context,"need to open location info for discovery bluetooth device in android6.0 version，otherwise find not！", Toast.LENGTH_LONG).show();
                //请求权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
            }
            return;
        }

    }

    // whether or not location is open, 位置是否打开
    public final boolean isGpsEnable(final Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            Log.i(TAG, "isGpsEnable: true");
            return true;
        }
        Log.i(TAG, "isGpsEnable: false");
        return false;
    }

    /**
     * 检测未授权的权限
     * @param permissions 权限列表
     * @return 未授权的
     */
    private String[] checkSelfPermissionArray(String... permissions) {
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if(checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED){
                    permissionList.add(permission);
                }
            }
        }

        String[] permissionArray = new String[permissionList.size()];
        for (int i =0; i < permissionArray.length; i ++){
            permissionArray[i] = permissionList.get(i);
        }
        return  permissionArray;
    }

    @SuppressLint("MissingPermission")
    private void initBLE(){
        Log.i(TAG, "initBLE: ...");
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "BLE is not supported", Toast.LENGTH_SHORT).show();
        }

        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        // 检查设备上是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "error bluetooth not supported", Toast.LENGTH_SHORT).show();
        }else{
            Log.i(TAG, "enable init ble ...");
            mBluetoothAdapter.enable();
            mManager = new BLEManager(this, mBluetoothAdapter);
        }
    }
}